const { ipcRenderer } = require('electron');
let videoElement = null;
let photoFrames = [];
let scanData = '';
let savePath = ''; // You can set a default save path here or get it from settings

document.addEventListener('DOMContentLoaded', () => {
    videoElement = document.getElementById('video');
    photoFrames = [
        document.getElementById('photo1'),
        document.getElementById('photo2'),
        document.getElementById('photo3'),
        document.getElementById('photo4')
    ];

    navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
        videoElement.srcObject = stream;
    }).catch(err => {
        console.error('Error accessing the camera:', err);
    });

    document.addEventListener('keydown', event => {
        if (event.key === 'Enter') {
            if (scanData.trim()) {
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                canvas.width = videoElement.videoWidth;
                canvas.height = videoElement.videoHeight;
                context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
                const dataURL = canvas.toDataURL('image/png');
                ipcRenderer.send('save-image', { dataURL, savePath, scanData });
                ipcRenderer.once('image-saved', (event, filePath) => {
                    displayPhoto(filePath);
                });
            }
            scanData = ''; // Reset scan data after processing
        } else {
            scanData += event.key; // Append key to scan data
        }
    });
});

function displayPhoto(filePath) {
    for (let frame of photoFrames) {
        if (!frame.hasChildNodes()) {
            const img = document.createElement('img');
            img.src = filePath;
            frame.appendChild(img);
            break;
        }
    }
}
